package com.loiane.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.loiane.dao.AccountDAO;
import com.loiane.model.Account;
import com.loiane.util.AccountUtil;

@Service
public class AccountService {

	private AccountDAO accountDAO;
	private AccountUtil util;

	@Transactional(readOnly = true)
	public List<Account> getAccountsList() {
		System.out.println("Account Service" + accountDAO.getAccounts());
		return accountDAO.getAccounts();
	}

	@Transactional
	public List<Account> create(Object data) {

		List<Account> newContacts = new ArrayList<Account>();

		List<Account> list = util.getAccountsFromRequest(data);

		for (Account account : list) {
			newContacts.add(accountDAO.saveAccount(account));
		}

		return newContacts;
	}

	public List<Account> update(Object data) {
		List<Account> returnAccounts = new ArrayList<Account>();
		List<Account> updateAccounts = util.getAccountsFromRequest(data);
		for (Account account : updateAccounts) {
			returnAccounts.add(accountDAO.saveAccount(account));
		}
		return returnAccounts;
	}

	@Transactional
	public void delete(Object data) {

		// it is an array - have to cast to array object
		if (data.toString().indexOf('[') > -1) {
			List<Integer> deleteAccounts = util.getListIdFromJSON(data);
			for (Integer id : deleteAccounts) {
				accountDAO.deleteAccount(id);
			}
		} else {
			Integer id = Integer.parseInt(data.toString());
			accountDAO.deleteAccount(id);
		}
	}

	@Autowired
	public void setAccountDAO(AccountDAO accountDAO) {
		this.accountDAO = accountDAO;
	}

	@Autowired
	public void setUtil(AccountUtil util) {
		this.util = util;
	}
}
